import { Models } from '../../../../common/typings/model'
import Config from '../../../../config/Config'
import KoaRouter from 'koa-router'
import Mysql from '../../../../core/Mysql'
import { Success } from '../../../../core/HttpException'
import { getTreeByList, lineToHumpObject, sort } from '../../../../common/utils/utils'
import Auth from '../../../../middlewares/Auth'
import Result from '../../../../common/utils/Result'
import RedisClient from '../../../../core/Redis'
const router = new KoaRouter({
  prefix: `${Config.api_prefix}system/role`,
})

router.post('/list', Auth.verifyTokenPermission, async (ctx: Models.Ctx) => {
  const { params, pageNum, pageSize } = ctx.request.body as unknown as Models.BasePaginationQuery
  const { name } = params
  RedisClient.redis.select(1)
  RedisClient.redis.hget('permission', '1').then((res) => {
    console.log(res)
  })
  const res = (
    await Mysql.command(`
      (SELECT
        id,
        name,
        \`describe\`,
        updated_at,
        parent_id,
        serial_num,
        permissions
      FROM
        role)
      ORDER BY
      updated_at DESC;

  `)
  ).results.map(lineToHumpObject)
  const records = getTreeByList(res, 0)
  const total: number = records.length
  if (pageNum > 1) {
    records.splice((pageNum - 1) * pageSize, pageSize)
  }
  const each = (arr: Models.TreeNode[]) => {
    sort(arr, 'serialNum', 'desc')
    arr.forEach((item) => {
      if (item.children) {
        each(item.children)
      }
    })
  }
  each(records)
  const data = Result.getPagination(records, total, pageSize, pageNum)
  throw new Success(data)
})

export default router
